package com.gnuc.thoth.app.screens;

import org.joda.time.DateTime;
import org.joda.time.Minutes;

import android.app.ExpandableListActivity;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract.Contacts;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnGroupClickListener;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.gnuc.thoth.R;
import com.gnuc.thoth.app.Main;
import com.gnuc.thoth.framework.Thoth;
import com.gnuc.thoth.framework.ThothLog;
import com.gnuc.thoth.framework.callbacks.ThothCallback;
import com.gnuc.thoth.framework.db.ThothDB;

public class CallMain extends ExpandableListActivity
{
	private ThothExpandableListAdapter	elAdapter	= null;
	private ExpandableListView				elView		= null;
	private Context							elContext;
	private static CallMain					instance		= null;
	private static int						tV_DO, tV_DI, tV_DP, tV_DR, tV_DM = 0;
	
	public static CallMain getInstance()
	{
		if (instance == null)
			instance = new CallMain();
		return instance;
	}
	
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		try
		{
			setContentView(R.layout.call_main);
			elContext = instance = this;
			elView = getExpandableListView();
			elAdapter = new ThothExpandableListAdapter();
			elView.setOnGroupClickListener(new OnGroupClickListener()
			{
				@Override
				public boolean onGroupClick(ExpandableListView elv, View view, int pos, long row)
				{
					return false;
				}
			});
			elView.setOnChildClickListener(new ExpandableListView.OnChildClickListener()
			{
				@Override
				public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id)
				{
					// Toast.makeText(elContext,
					// String.valueOf(v.getTag(Thoth.APP)),Toast.LENGTH_LONG).show();
					return true;
				}
			});
			elView.addHeaderView(View.inflate(this, R.layout.call_layout, null), null, false);
			elView.setAdapter(elAdapter);
			elView.setDivider(getResources().getDrawable(R.drawable.row_gradient1));
			elView.setDividerHeight(1);
			elView.setChildDivider(getResources().getDrawable(R.drawable.row_gradient2));
			elView.setFooterDividersEnabled(true);
		}
		catch (Exception e)
		{
			ThothLog.e(e);
			Main.getInstance().mainHandler.sendEmptyMessage(-1);
		}
	}
	
	@Override
	public void onResume()
	{
		super.onResume();
		Thoth.cx = this;
		updateStatistics();
	}
	
	@Override
	public void onPause()
	{
		super.onPause();
	}
	
	public class ThothExpandableListAdapter extends BaseExpandableListAdapter
	{
		private Integer[]		explist_parents;
		private String[][][]	explist_children;
		
		public ThothExpandableListAdapter()
		{
			explist_parents = new Integer[]{R.layout.explist_c_top_out, R.layout.explist_c_top_in};
			explist_children = new String[][][]{{{"", "", ""}, {"", "", ""}, {"", "", ""}, {"", "", ""}, {"", "", ""}}, {{"", "", ""}, {"", "", ""}, {"", "", ""}, {"", "", ""}, {"", "", ""}}};
		}
		
		@Override
		public Object getChild(int groupPosition, int childPosition)
		{
			return explist_children[groupPosition][childPosition];
		}
		
		@Override
		public long getChildId(int groupPosition, int childPosition)
		{
			return childPosition;
		}
		
		@Override
		public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent)
		{
			RelativeLayout child = (RelativeLayout) View.inflate(elContext, R.layout.explist_c_childrow, null);
			String cN = explist_children[groupPosition][childPosition][0];
			String cD = explist_children[groupPosition][childPosition][1];
			String cT = explist_children[groupPosition][childPosition][2];
			cN = (cN.equals("")) ? " - " : cN;
			if (!cD.equals(""))
			{
				Float seconds = Float.parseFloat(cD);
				cD = (seconds > 59) ? (Math.round(seconds / 60) + " min.") : (seconds + " sec.");
			}
			else
				cD = "( - )";
			cT = (cT.equals("")) ? "" : "[ " + cT + " nos. ]";
			TextView tv = ((TextView) child.findViewById(R.id.t_c_child_name_label_id));
			tv.setText(cN);
			tv.setVisibility(View.VISIBLE);
			tv = (TextView) child.findViewById(R.id.t_c_child_duration_label_id);
			tv.setText(cD);
			tv.setVisibility(View.VISIBLE);
			tv = (TextView) child.findViewById(R.id.t_c_child_quantity_label_id);
			tv.setText(cT);
			tv.setVisibility(View.VISIBLE);
			child.setTag(Thoth.APP, cN);
			return child;
		}
		
		@Override
		public int getChildrenCount(int groupPosition)
		{
			return explist_children[groupPosition].length;
		}
		
		@Override
		public Object getGroup(int groupPosition)
		{
			return explist_parents[groupPosition];
		}
		
		@Override
		public int getGroupCount()
		{
			return explist_parents.length;
		}
		
		@Override
		public long getGroupId(int groupPosition)
		{
			return groupPosition;
		}
		
		@Override
		public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent)
		{
			return (RelativeLayout) View.inflate(elContext, (Integer) getGroup(groupPosition), null);
		}
		
		@Override
		public boolean hasStableIds()
		{
			return true;
		}
		
		@Override
		public boolean isChildSelectable(int groupPosition, int childPosition)
		{
			return true;
		}
	}
	
	public void updateStatistics()
	{
		updateDataSet(elAdapter, Thoth.Settings.APP_LOG_FILTER, new ThothCallback()
		{
			@Override
			public void handle(boolean result)
			{
				runOnUiThread(new Runnable()
				{
					@Override
					public void run()
					{
						elAdapter.notifyDataSetChanged();
					}
				});
			}
		});
	}
	
	void updateDataSet(ThothExpandableListAdapter tela, int filter, ThothCallback callback)
	{
		if (filter == 0)
		{
			Minutes diffMins = Minutes.minutesBetween(new DateTime(), new DateTime(Thoth.Settings.APP_LAST_SYNC_THOTH));
			if (diffMins.getMinutes() > 5)
			{}
		}
		int x;
		boolean result = false;
		Cursor cR = null;
		ThothDB dbA = new ThothDB(elContext);
		try
		{
			dbA.open();
			SQLiteDatabase db = dbA.getDb();
			cR = db.query(true, ThothDB.table_APP_CALL_STAT, null, ThothDB.col_A_S_C_FILTER + "=" + filter, null, null, null, null, null);
			if (cR != null && cR.moveToFirst())
			{
				tV_DO = cR.getInt(cR.getColumnIndexOrThrow(ThothDB.col_A_S_C_TOTAL_OUTBOUND_CALLS)) / 60;
				tV_DI = cR.getInt(cR.getColumnIndexOrThrow(ThothDB.col_A_S_C_TOTAL_INBOUND_CALLS)) / 60;
				tV_DP = cR.getInt(cR.getColumnIndexOrThrow(ThothDB.col_A_S_C_TOTAL_PLACED_CALLS));
				tV_DR = cR.getInt(cR.getColumnIndexOrThrow(ThothDB.col_A_S_C_TOTAL_RECEIVED_CALLS));
				tV_DM = cR.getInt(cR.getColumnIndexOrThrow(ThothDB.col_A_S_C_TOTAL_MISSED_CALLS));
				
				runOnUiThread(new Runnable()
				{
					@Override
					public void run()
					{
						((TextView) findViewById(R.id.t_c_duration_out_data_id)).setText(String.valueOf(tV_DO));
						((TextView) findViewById(R.id.t_c_duration_in_data_id)).setText(String.valueOf(tV_DI));
						((TextView) findViewById(R.id.t_c_total_out_data_id)).setText(String.valueOf(tV_DP));
						((TextView) findViewById(R.id.t_c_total_in_data_id)).setText(String.valueOf(tV_DR));
						((TextView) findViewById(R.id.t_c_total_missed_data_id)).setText(String.valueOf(tV_DM));
					}
				});
			}
			tela.explist_children = new String[][][]{{{"", "", ""}, {"", "", ""}, {"", "", ""}, {"", "", ""}, {"", "", ""}}, {{"", "", ""}, {"", "", ""}, {"", "", ""}, {"", "", ""}, {"", "", ""}}};
			cR = db.query(true, ThothDB.table_APP_CALL_RANK, null, "(" + ThothDB.col_A_R_C_TYPE + "=0" + ")" + "AND" + "(" + ThothDB.col_A_R_C_FILTER + "=" + filter + ")", null, null, null, ThothDB.col_A_R_C_DURATION + " DESC", null);
			if (cR != null && cR.moveToFirst())
			{
				x = 0;
				do
					tela.explist_children[0][x++] = new String[]{lookupContact(cR.getString(cR.getColumnIndexOrThrow(ThothDB.col_A_R_C_CONTACT))), cR.getString(cR.getColumnIndexOrThrow(ThothDB.col_A_R_C_DURATION)), cR.getString(cR.getColumnIndexOrThrow(ThothDB.col_A_R_C_CONTACTED))};
				while (cR.moveToNext() && x < 5);
			}
			cR = db.query(true, ThothDB.table_APP_CALL_RANK, null, "(" + ThothDB.col_A_R_C_TYPE + "=1" + ")" + "AND" + "(" + ThothDB.col_A_R_C_FILTER + "=" + filter + ")", null, null, null, ThothDB.col_A_R_C_DURATION + " DESC", null);
			if (cR != null && cR.moveToFirst())
			{
				x = 0;
				do
					tela.explist_children[1][x++] = new String[]{lookupContact(cR.getString(cR.getColumnIndexOrThrow(ThothDB.col_A_R_C_CONTACT))), cR.getString(cR.getColumnIndexOrThrow(ThothDB.col_A_R_C_DURATION)), cR.getString(cR.getColumnIndexOrThrow(ThothDB.col_A_R_C_CONTACTED))};
				while (cR.moveToNext() && x < 5);
			}
			result = true;
		}
		catch (Exception e)
		{
			// ThothLog.e(e);
		}
		finally
		{
			cR.close();
			dbA.close();
			callback.handle(result);
		}
		return;
	}
	
	String lookupContact(String lookupKey)
	{
		String cLookupKey = lookupKey;
		Uri lookupUri = Uri.withAppendedPath(Contacts.CONTENT_LOOKUP_URI, lookupKey);
		Cursor cR = null;
		try
		{
			cR = getContentResolver().query(lookupUri, new String[]{Contacts.DISPLAY_NAME}, null, null, null);
			cR.moveToFirst();
			cLookupKey = cR.getString(0);
		}
		catch (Exception e)
		{}
		finally
		{
			if (cR != null)
				cR.close();
		}
		return cLookupKey;
	}
}
